<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>FaculTimes Web Frontend</title>
	<!-- syntax help from jquerymobile.com and jQuery Mobile Web Dev Essentials 2E text -->
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<!-- jQuery Mobile -->
	<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.css" />
	<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
	<script src="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.js"></script>

	<!-- DateTimePicker functionality (from stevenbooks.com) -->
	<!-- requires jQuery UI-->
	<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css" />
	<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
	<script src="jquery-ui-timepicker-addon.js"></script>
	<link rel="stylesheet" href="dtp_style.css" type="text/css" media="all" />

	<!-- jQuery Validate for form editing -->
	<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>

	<!-- form validation jQuery and CSS cobbled together from old lectures, stackoverflow posts, 
	http://www.gajotres.net/document-onpageinit-vs-document-ready/, and probably 
	a dozen other sites I'm not remembering at the moment -->
	<script>
		$(document).on('pageinit', '#optPage', function() {
			$("#frm3").validate({
				errorPlacement: function (error, element) {
					error.appendTo(element.parent().prev());
				}
			});
		});
	</script>

	<!-- make form errors red + on its own line -->
	<style>
	label.error {
		color: red; 
		display: block;
	}
	</style>
	
	<!-- stretch buttons -->
	<style>	
	.btn {
		display: block;
		width:100%;
	} 
	</style>
	
	<script> // Dynamic form field generator, structure adapted from Charlie Griefer's blog post, found
			 // at http://charlie.griefer.com/blog/2009/09/17/jquery-dynamically-adding-form-elements/ 

	////////// for Opt form //////////
	$(document).ready(function() {
		$('#frm3btnAdd').click(function() {
			var num = $('.frm3clonedInput').length;	// array length = # of "clone-able" divs that currently exist
			var newNum	= new Number(num + 1); 		// gives us a # (i.e., index+1) to enumerate the next div being added

			//clone() old element (=div), then set the new element (=div)'s id based on newNum value
			var newElem = $('#frm3input' + num).clone().attr('id', 'frm3input' + newNum); 

			//inside new element (=div), set new form field id="" and name="" values based on newNum
			//(...note that the form input field is the div's 1st and only child)
			newElem.children(':first').children(':first').attr('id', 'frm3name' + newNum);
			newElem.children(':first').children(':first').attr('name', 'name' + newNum);;
			// .find("input:text").val("");


			//insert the new div after last "clone-able" input field
			$('#frm3input' + num).after(newElem);
			$('#frm3name' + newNum).val('');

			// enable the "delete" button (since we now have > 1 elem)
			$('#frm3btnDel').parent().show();
			
			// if max # elements have been added (10), disable the "add" button
			if (newNum == 10) {
				$('#frm3btnAdd').parent().hide();
			}
		});

		$('#frm3btnDel').click(function() {
			var num = $('.frm3clonedInput').length;	// array length = # of "clone-able" divs that currently exist

			// remove the last element (div) and decrement num (for eval later)
			$('#frm3input' + num).remove(); 
			num--;

			// enable the "add" button (since we now have < max # elem's)
			$('#frm3btnAdd').parent().show();

			// if only 1 element remains, disable the "remove" button
			if (num == 1) {
				$('#frm3btnDel').parent().hide();
			}
		});  

		//initially, disable the "delete" button (since at least 1 username is required)
		$('#frm3btnDel').parent().hide();
	});
	</script>  

	<script> ///// Datetimepicker JS needed /////
		$(document).ready(function(){
			$('.datetimepicker').datetimepicker({});
		});
	</script>

	<style>	/* Datetimepicker CSS needed */
		.ui-timepicker-div .ui-widget-header { margin-bottom: 8px; }
		.ui-timepicker-div dl { text-align: left; }
		.ui-timepicker-div dl dt { height: 25px; margin-bottom: -25px; }
		.ui-timepicker-div dl dd { margin: 0 10px 10px 65px; }
		.ui-timepicker-div td { font-size: 90%; }
		.ui-tpicker-grid-label { background: none; border: none; margin: 0; padding: 0; }
		#ui-datepicker-div { font-size: 12px; }
	</style>

</head>

<body>
	<!--///////////////// HOMEPAGE /////////////////-->
	<div data-role="page" data-theme="a" id="homePage">
		<div data-role="header">
			<h1>:: Welcome to FaculTimes ::</h1>
		</div>
		<div data-role="content">
			<div data-role="navbar">
				<ul>
					<li><a href="#homePage" class="ui-btn-active ui-state-persist">Instructions</a></li>
					<li><a href="#opt3Page">Query</a></li>
				</ul>								
			</div><!-- end navbar -->

			<!-- Instructions -->
			<h3>Instructions:</h3>
			Enter your query parameters on the Query page.  Depending on the input provided, queries will return information indiciating:<br />
			<ul>
				<li>The availability of any given user (by username) within a specified window,</li>
				<li>All users specified who are available for the entire duration of a specified window, as well as </li>
				<li>The times when all users specified are available within a particular specified window. </li>
			</ul>

			<p>When you are ready to search, select the "Query" button above.</p>

		</div> <!-- end content -->
	</div> <!-- end #homePage -->

	<!--///////////////// OPTIONS PAGE ///////////////-->
	<div data-role="page" data-theme="a" id="opt3Page">
		<div data-role="header">
			<h1>:: FaculTimes Query ::</h1>
		</div>

		<div data-role="content">
			<div data-role="navbar">
				<ul>
					<li><a href="#homePage">Instructions</a></li>
					<li><a href="#opt3Page" class="ui-btn-active ui-state-persist">Query</a></li>
				</ul>								
			</div><!-- end navbar -->

			<!---------Options form---------->
			<h3>Enter Query Information:</h3>
				Enter a username (or usernames) to find general availability.  If a time window is also specified, Facultimes will list:<br />
				<ul>
					<li> users available for the entire duration of the window, and</li>
					<li> times when all users are available. </li>
				</ul>
				Results will be displayed below.<br />

			<div class="ui-field-contain">
				<form id="frm3" method="post">
					<div>
						<label for="opt3startwindow"><strong>Window Start Time:</strong></label>
						<input class="datetimepicker" id="opt3startwindow" name="startwindow" type="text" size=25 />
					</div>
			
					<div>
						<label for="opt3endwindow"><strong>Window End Time:</strong></label>
						<input class="datetimepicker" id="opt3endwindow" name="endwindow" type="text" size=25 />
					</div>

					<!-- ...and the dynamic bit... -->
					<strong>Users to Include in Search (max 10):</strong><br />
					
					<div id="frm3input1" class="frm3clonedInput" style="margin-bottom:4px;">
						<input id="frm3name1" name="name1" type="text" placeholder="Enter username" />
					</div>

					<!-- Add/Del buttons -->
					<div> <input class="btn" id="frm3btnAdd" type="button" value="Add Another User" /> </div> 
					<div> <input class="btn" id="frm3btnDel" type="button" value="Remove User" /> </div>
					<div> <input class="btn" id="opt3submit" name="opt3submit" type="submit" value="Go" /> </div>
				</form>
			</div>

			<!---------Results---------->
			<div class="ui-field-contain" id="resultswrapper3">
				<h2 id="resultsheading3"></h2>
				<h3 id="errorfield3"></h3>
				<h3 id="timesheading3"></h3>
				<ul id="timeslist3">
				</ul>
				<h3 id="attendeesheading3"></h3>
				<ul id="attendeeslist3">
				</ul>
			</div>
		</div> <!-- end content -->
	</div> <!-- end options page -->

	
	<!--///////////////// FORM SUBMISSION HANDLING ///////////////-->
	<script>
	// Define what the form submit should do, i.e.,:
	// 	- send via post to the URL,
	// 	- serialize the form data before sending,
	// 	- on success, call displayOption3() using the parameter "data", which is what comes back from the cgi file, and
	// 	- prevent redirection.
	$("#frm3").submit( function () {    
		$.post(
			'http://web.engr.oregonstate.edu/cgi-bin/cgiwrap/tannerm/facultimes/matt/provider.cgi',
			$(this).serialize(),
			function(data){
				//alert(data);
				// alert(JSON.stringify(data));
				displayOption3(data); //do something with the data
			},
			'json'
		);
		return false;   
	});
	
	// Function to display the JSON data returned.  JSON data is accessible with the . operator
	// or [], e.g., data.times[0].start gives the start time/date for the first available
	// window in the times array.  It can also be accessed using data['times'][0]['start'].  
	function displayOption3(data){
		$("#resultsheading3").empty()
		$("#errorfield3").empty()
		$("#timesheading3").empty();
		$("#timeslist3").empty();
		$("#attendeesheading3").empty();
		$("#attendeeslist3").empty();

		// display error message if returned
		if(data['error']){
			var error = data['error'];
			$("#errorfield3").text(error).css('color', 'red');
			return
		}

		// otherwise:
		$("#resultsheading3").text("Results")

		// display times
		$("#timesheading3").text("Available Times");	
		if(data['times'].length == 0){
			$("#timeslist3").append("<li>No times available to all selected users within window.</li>")
		}
		for(var index in data.times){
			var time = "<li>" + data.times[index].start + " - " + data.times[index].end + "</li>";
			$("#timeslist3").append(time);
		}

		// display attendees
		$("#attendeesheading3").text("Attendees");
		if(data['attendees'].length == 0){
			$("#attendeeslist3").append("<li>None of the selected users are available for the entire window.</li>")
		}		
		for(var index in data.attendees){
			var attendee = "<li>" + data.attendees[index].name + "</li>";
			$("#attendeeslist3").append(attendee);
		} 
	}

	</script>
</body>
</html>
